package adminService

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	adminDto "news_for_deepseek_interface/dto/admin"
	"news_for_deepseek_interface/model"
	adminModel "news_for_deepseek_interface/model/admin"
	"time"
)

func Login(params adminDto.LoginRequest) (response adminDto.LoginResponse, err error) {

	db := model.GetInstance().GetDB()

	//用户查询
	var adminStruct adminModel.AdminStruct
	err = db.Model(&adminModel.AdminStruct{}).
		Where("username = ? or mobile = ?", params.Username, params.Username).
		First(&adminStruct).Error
	if err != nil {
		err = fmt.Errorf("登录失败: %v", err)
		return
	}

	//状态判断
	if adminStruct.Status != 1 {
		err = errors.New("账号已禁用,请联系管理员")
		return
	}

	if adminStruct.Expires.Before(time.Now()) {
		err = fmt.Errorf("您的账号已过期，请联系管理员")
		return
	}

	//密码校验
	data := []byte(params.Password + "|" + adminStruct.Salt)
	hash := md5.Sum(data)
	hashString := hex.EncodeToString(hash[:])
	if hashString != adminStruct.Password {
		err = errors.New("登录失败")
		return
	}

	//刷新token
	accessToken, refreshToken, expires, err := UpdateAccessToken(adminStruct.Id)
	if err != nil {
		err = fmt.Errorf("刷新token失败: %v", err)
		return
	}

	response = adminDto.LoginResponse{
		Username:     adminStruct.Username,
		AccessToken:  accessToken,
		RefreshToken: refreshToken,
		Expires:      expires,
	}
	return
}
